package com.cloudcc.mobile.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.entity.DingWei;
import com.cloudcc.mobile.manager.ConfigManager;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.net.KeepSessionClient;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.litesuits.android.log.Log;

/**
 * 后台定时上传坐标位置service
 */
public class DingWeiService extends Service {
	private DingWei dw;
	private DWService service = new DWService();
	private Timer mTimer;
	private TimerTask mtask;
	int locationTime;
	public List<DingWei> list = new ArrayList<DingWei>();

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.d("kaishidingwei", "定位开始");
		LogUtils.d("app", "定位服务开启");
		// 上报时间
		locationTime = ConfigManager.getInstance().getLocationTime();
		super.onCreate();
		Log.d("schedule", AppContext.locationtime + "::" + locationTime);
		mTimer = new Timer();
		mtask = new LocTask();
		// 获取位置的时间间隔
		mTimer.schedule(mtask, 0, AppContext.locationtime);// 1000毫秒= 1秒;
//		 mTimer.schedule(mtask, 0, 5000);
		Log.d("diyicilist", GsonUtil.Object2Json(list));
		// handler.postDelayed(runnable, 5000 * 2);
		handler.postDelayed(runnable, locationTime);
//		 handler.postDelayed(runnable, 25000);
	}

	Handler handler = new Handler();
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// handler自带方法实现定时器
			try {
				handler.postDelayed(this, locationTime);
				Log.d("listlength","上传"+GsonUtil.Object2Json(list));
				Log.d("shujushishenme",
						"shujushi:" + GsonUtil.Object2Json(list));
				new MyTask().execute(GsonUtil.Object2Json(list).substring(1,
						GsonUtil.Object2Json(list).length() - 1));
				
				Log.d("daodishibushihand", "通过handler上传一次位置和获取位置时间"
						+ AppContext.locationtime);
				Log.d("listlength","上传成功");
			} catch (Exception e) {
				e.printStackTrace();
				Log.d("listlength","上传失败");
				Log.d("daodishibushihand", "通过handler上传一次位置和获取位置时间失败"
						+ AppContext.locationtime);
				System.out.println("exception...");
			}
		}
	};

	private class LocTask extends TimerTask {
		@Override
		public void run() {
			Log.d("daodishibushihand", "异步任务获取位置和获取位置时间间隔"
					+ AppContext.locationtime);
			if (NetWork.detect(DingWeiService.this)) {
				KeepSessionClient.getInstance().refreshServerBinding();
				LocationManager.getInstance().registerListener(mListener);
				LocationManager.getInstance().requestLocal();
				Log.d("listlength","判断是否有望");
			} else {
				Log.d("listlength","没有望");
				LocationManager.getInstance().stopRequestLocal();
			}
		}

	}

	private void stopTask() {
		LocationManager.getInstance().stopRequestLocal();
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mtask != null) {
			mtask.cancel();
			mTimer = null;
		}
	}

	@Override
	public void onDestroy() {
		Log.d("guanbiservice", "关闭周期");
		LocationManager.getInstance().unregisterlistener(mListener);
		new MyTask().execute(GsonUtil.Object2Json(list).substring(1,
				GsonUtil.Object2Json(list).length() - 1));
		list.clear();
		try {
			if (AppContext.isStopLocation) {
				stopTask();
				list.clear();
				handler.removeCallbacks(runnable);
				super.onDestroy();
			} else {
				Intent intent = new Intent(this, DingWeiService.class);
				startService(intent);
			}
		} catch (Exception e) {
			Tools.handle(e);
		}
	}

	private BDLocationListener mListener = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (null != location
					&& location.getLocType() != BDLocation.TypeServerError) {
				LocationManager.getInstance().stopRequestLocal();
				LocationManager.log(location);
				uploadeLoc(location);
				// Log.d("location",
				// "位置是："+location.getLatitude()+location.getLongitude());
				Log.d("listlength","定位不为空");
			} else {
				Log.d("listlength","定位空");
			}
		}
	};
	int i = 1;

	private void uploadeLoc(BDLocation location) {

		dw = new DingWei();
		dw.setYg(UserManager.getManager().getUser().userId);// 员工id
		String jingweidu = location.getLongitude() + ","
				+ location.getLatitude();
		dw.setWz(jingweidu);// 经纬度
		dw.setMs(LocationManager.getDetailAddr(location, false));
		dw.setSj(Tools.getNowTime());
		// Log.d("uoloadlocation", "weizhi:"+jingweidu);
		list.add(dw);
		Log.d("panduanshifoukong", jingweidu+"::"+LocationManager.getDetailAddr(location, false));
		 Log.d("listlength",dw.getSj());
		if (i == 1) {
			new MyTask().execute(GsonUtil.Object2Json(list).substring(1,
					GsonUtil.Object2Json(list).length() - 1));
			Log.d("daodishibushihand", "第一次登录的时候上报位置");

		}

	}

	// 联网上传位置
	class MyTask extends AsyncTask<String, Void, String> {
		protected String doInBackground(String... params) {
			String jsonstring = "";

			try {
				String data = params[0];
				// Log.d("uoloadlocation", "weizhiMyTask:"+data);
				jsonstring = service.insert(data);
				list.clear();
				if (i != 1) {
					String jsonstring1 = service.huoqu();
					Long timenew = null;
					if (!"".equals(jsonstring1) && jsonstring1 != null) {
						timenew = Long.parseLong(jsonstring1.trim());
					}

					if (timenew != null
							&& AppContext.locationtime != timenew * 1000 * 60) {
						stopTask();
						if (mTimer == null) {
							mTimer = new Timer();
						}

						mtask = new LocTask();

						if (mTimer != null && mtask != null) {
							mTimer.schedule(mtask, 0, timenew * 1000 * 60);

						}

					}
				}
				Log.d("daodishibushihand", "上报位置成功" + jsonstring);
				i = 2;
				return jsonstring;
			} catch (Exception e) {
				Tools.handle(e);
				Log.d("daodishibushihand", e.toString());
			}
			return jsonstring;
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}
	// Handler handler2 = new MyHandler();
	// class MyHandler extends Handler {
	// public MyHandler() {
	// }
	//
	// public MyHandler(Looper L) {
	// super(L);
	// }
	//
	// // 子类必须重写此方法，接受数据
	// @Override
	// public void handleMessage(Message msg) {
	// // TODO Auto-generated method stub
	// super.handleMessage(msg);
	//
	//
	// }
	// }
}
